
<!DOCTYPE html>
<html lang="zh-Hans" class="loading">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>前端代码规范-JS篇 - 默默默默燃</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google" content="notranslate" />
    <meta name="keywords" content="TriDiamond Obsidian,"> 
    <meta name="description" content="一枚前端搬砖队队员的记录册,更多前端代码规范请移步

如果是个人或者小作坊开发，其实这些所谓的编码规范也没啥意思，因为大家写好的代码直接就给扔到网上去了，很少有打包、压缩、校检等过程，别人来修改你代码的情况也比较少。但是，对于,"> 
    <meta name="author" content="张白告丶"> 
    <link rel="alternative" href="atom.xml" title="默默默默燃" type="application/atom+xml"> 
    <link rel="icon" href="/img/favicon.png"> 
    <link href="https://fonts.loli.net/css?family=Roboto+Mono|Rubik&display=swap" rel="stylesheet">
    
<link rel="stylesheet" href="//at.alicdn.com/t/font_1429596_nzgqgvnmkjb.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.7.2/animate.min.css">

    
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/codemirror.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/theme/dracula.css">

    
<link rel="stylesheet" href="/css/obsidian.css">

    
<link rel="stylesheet" href="/css/ball-atom.min.css">

<meta name="generator" content="Hexo 4.2.0"></head>


<body class="loading">
    <div class="loader">
        <div class="la-ball-atom la-2x">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>
    <span id="config-title" style="display:none">默默默默燃</span>
    <div id="loader"></div>
    <div id="single">
    <div class="scrollbar gradient-bg-rev"></div>
<div id="top" style="display: block;">
    <div class="bar" style="width: 0;"></div>
    <div class="navigation animated fadeIn fast delay-1s">
        <img id="home-icon" class="icon-home" src="/img/favicon.png" alt="" data-url="https://zhanghao-web.github.io">
        <div id="play-icon" title="Play/Pause" class="iconfont icon-play"></div>
        <h3 class="subtitle">前端代码规范-JS篇</h3>
        <div class="social">
            <!--        <div class="like-icon">-->
            <!--            <a href="javascript:;" class="likeThis active"><span class="icon-like"></span><span class="count">76</span></a>-->
            <!--        </div>-->
            <div>
                <div class="share">
                    
                        <a href="javascript:;" class="iconfont icon-share1"></a>
                        <div class="share-component-cc" data-disabled="facebook,douban,linkedin,diandian,tencent,google"></div>
                    
                </div>
            </div>
        </div>
    </div>
</div>

    <div class="section">
        <div class=article-header-wrapper>
    <div class="article-header">
        <div class="article-cover animated fadeIn" style="
            animation-delay: 600ms;
            animation-duration: 1.2s;
            background-image: 
                radial-gradient(ellipse closest-side, rgba(0, 0, 0, 0.65), #100e17),
                url(/img/cover.jpg) ">
        </div>
        <div class="else">
            <p class="animated fadeInDown">
                
                <a href="/categories/Standard"><b>「
                    </b>STANDARD<b> 」</b></a>
                
                April 19, 2018
            </p>
            <h3 class="post-title animated fadeInDown"><a href="/2018/04/19/Record/%E5%89%8D%E7%AB%AF%E4%BB%A3%E7%A0%81%E8%A7%84%E8%8C%83-JS%E7%AF%87/" title="前端代码规范-JS篇" class="">前端代码规范-JS篇</a>
            </h3>
            
            <p class="post-count animated fadeInDown">
                
                <span>
                    <b class="iconfont icon-text2"></b> <i>Words count</i>
                    31k
                </span>
                
                
                <span>
                    <b class="iconfont icon-timer__s"></b> <i>Reading time</i>
                    29 mins.
                </span>
                
                
                
                <span id="busuanzi_container_page_pv">
                    <b class="iconfont icon-read"></b> <i>Read count</i>
                    <span id="busuanzi_value_page_pv">0</span>
                </span>
                
            </p>
            
            
            <ul class="animated fadeInDown post-tags-list" itemprop="keywords"><li class="animated fadeInDown post-tags-list-item"><a class="animated fadeInDown post-tags-list-link" href="/tags/Record/" rel="tag">Record</a></li></ul>
            
        </div>
    </div>
</div>

<div class="screen-gradient-after">
    <div class="screen-gradient-content">
        <div class="screen-gradient-content-inside">
            <div class="bold-underline-links screen-gradient-sponsor">
                <p>
                    <span class="animated fadeIn delay-1s"></span>
                </p>
            </div>
        </div>
    </div>
</div>

<div class="article">
    <div class='main'>
        <div class="content markdown animated fadeIn">
            <p><a href="https://github.com/zhanghao-web/spec" target="_blank" rel="noopener">更多前端代码规范请移步</a></p>
<hr>
<p>如果是个人或者小作坊开发，其实这些所谓的编码规范也没啥意思，因为大家写好的代码直接就给扔到网上去了，很少有打包、压缩、校检等过程，别人来修改你代码的情况也比较少。但是，对于一定规模的团队来说，这些东西还是挺有必要的！一个是保持代码的整洁美观，同时良好的代码编写格式和注释方式可以让后来者很快地了解你代码的大概思路，提高开发效率。</p>
<h1 id="不规范写法举例"><a href="#不规范写法举例" class="headerlink" title="不规范写法举例"></a>不规范写法举例</h1><ol>
<li>句尾没有分号<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> isHotel = json.type == <span class="string">"hotel"</span> ? <span class="literal">true</span> : <span class="literal">false</span></span><br></pre></td></tr></table></figure></li>
<li>变量命名各种各样<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> is_hotel;</span><br><span class="line"><span class="keyword">var</span> isHotel;</span><br><span class="line"><span class="keyword">var</span> ishotel;</span><br></pre></td></tr></table></figure></li>
<li>if 缩写<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (isHotel)</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="literal">true</span>)</span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="literal">false</span>)</span><br></pre></td></tr></table></figure></li>
<li>使用 eval<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> json = <span class="built_in">eval</span>(jsonText);</span><br></pre></td></tr></table></figure></li>
<li>变量未定义到处都是<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> isHotel = <span class="string">'true'</span>;</span><br><span class="line">    .......</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> html = isHotel ? <span class="string">'&lt;p&gt;hotel&lt;/p&gt;'</span> : <span class="string">""</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li>超长函数<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> isHotel = <span class="string">'true'</span>;</span><br><span class="line">    <span class="comment">//....... 此处省略500行</span></span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<a id="more"></a>
<h1 id="前端规范之JavaScript"><a href="#前端规范之JavaScript" class="headerlink" title="前端规范之JavaScript"></a>前端规范之JavaScript</h1><h2 id="变量、常量、类的命名按（必须）以下规则执行："><a href="#变量、常量、类的命名按（必须）以下规则执行：" class="headerlink" title="变量、常量、类的命名按（必须）以下规则执行："></a>变量、常量、类的命名按（必须）以下规则执行：</h2></li>
</ol>
<p>　　1） 变量：必须采用骆驼峰的命名且首字母小写<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 正确的命名</span></span><br><span class="line"> <span class="keyword">var</span> isHotel,</span><br><span class="line">     isHotelBeijing,</span><br><span class="line">     isHotelBeijingHandian;</span><br><span class="line"></span><br><span class="line"> <span class="comment">// 不推荐的命名</span></span><br><span class="line"> <span class="keyword">var</span> is_Hotel,</span><br><span class="line">     ishotelbeijing,</span><br><span class="line">     IsHotelBeiJing;</span><br></pre></td></tr></table></figure><br>　　2） 常量：必须采用全大写的命名，且单词以_分割，常量通常用于ajax请求url，和一些不会改变的数据<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 正确的命名</span></span><br><span class="line">  <span class="keyword">var</span> HOTEL_GET_URL = <span class="string">'http://map.baidu.com/detail'</span>,</span><br><span class="line">      PLACE_TYPE = <span class="string">'hotel'</span>;</span><br></pre></td></tr></table></figure><br>　　3） 类：必须采用骆驼峰的命名且首字母大写，如：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 正确的写法</span></span><br><span class="line"> <span class="keyword">var</span> FooAndToo = <span class="function"><span class="keyword">function</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">     <span class="keyword">this</span>.name = name;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="if中的空格，先上例子"><a href="#if中的空格，先上例子" class="headerlink" title="if中的空格，先上例子"></a>if中的空格，先上例子</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//正确的写法</span></span><br><span class="line"> <span class="keyword">if</span> (isOk) &#123;</span><br><span class="line">     <span class="built_in">console</span>.log(<span class="string">"ok"</span>);</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="comment">//不推荐的写法</span></span><br><span class="line"> <span class="keyword">if</span>(isOk)&#123;</span><br><span class="line">     <span class="built_in">console</span>.log(<span class="string">"ok"</span>);</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>()中的判断条件前后都(必须)加空格</li>
<li>()里的判断前后(禁止)加空格，如：正确的写法: if (isOk)；不推荐的写法: if ( isOk )<br>　　2）switch中的空格, 先上例子<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//正确的写法</span></span><br><span class="line">  <span class="keyword">switch</span>(name) &#123;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">"hotel"</span>:</span><br><span class="line">          <span class="built_in">console</span>.log(name);</span><br><span class="line">          <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">case</span> <span class="string">"moive"</span>:</span><br><span class="line">          <span class="built_in">console</span>.log(name);</span><br><span class="line">          <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">default</span>:</span><br><span class="line">          <span class="comment">// code</span></span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="for中的空格，先上例子"><a href="#for中的空格，先上例子" class="headerlink" title="for中的空格，先上例子"></a>for中的空格，先上例子</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">// 正确的写法</span></span><br><span class="line">  <span class="keyword">var</span> names = [<span class="string">"hotel"</span>, <span class="string">"movie"</span>],</span><br><span class="line">      i, len;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (i=<span class="number">0</span>, len=names.length; i &lt; len; i++) &#123;</span><br><span class="line">      <span class="comment">// code</span></span><br><span class="line">  &#125;  </span><br><span class="line"><span class="string">``</span><span class="string">` </span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">* for后（必须）加空格</span></span><br><span class="line"><span class="string">* 每个;后（必须）加空格</span></span><br><span class="line"><span class="string">* ()中禁止用var声明变量; 且变量的赋值 = 前后（禁止）加空格</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">## function 中的空格, 先上例子</span></span><br><span class="line"><span class="string">`</span><span class="string">``</span>javascript</span><br><span class="line"> <span class="comment">// 正确的写法</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">call</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> cell = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">  &#125;;</span><br></pre></td></tr></table></figure>
<ul>
<li>参数的反括号后（必须）加空格</li>
<li>function 后（必须）加空格</li>
</ul>
<h2 id="var-中空格及定义，先上例子"><a href="#var-中空格及定义，先上例子" class="headerlink" title="var 中空格及定义，先上例子"></a>var 中空格及定义，先上例子</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 一个推荐的var写法组</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span>(<span class="params">res</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">var</span> code = <span class="number">1</span> + <span class="number">1</span>,</span><br><span class="line">          json = <span class="built_in">JSON</span>.parse(res),</span><br><span class="line">          type, html;</span><br><span class="line"></span><br><span class="line">      <span class="comment">// code</span></span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>声明变量 = 前后（必须）添加空格</li>
<li>每个变量的赋值声明以,结束后（必须）换行进行下一个变量赋值声明<br><em>（推荐）将所有不需要进行赋值的变量声明放置最后一行，且变量之间不需要换行
</em>（推荐）当一组变量声明完成后，空一行后编写其余代码</li>
</ul>
<h2 id="在同一个函数内部，局部变量的声明必须置于顶端"><a href="#在同一个函数内部，局部变量的声明必须置于顶端" class="headerlink" title="在同一个函数内部，局部变量的声明必须置于顶端"></a>在同一个函数内部，局部变量的声明必须置于顶端</h2><p>因为即使放到中间，js解析器也会提升至顶部（hosting）<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 正确的书写</span></span><br><span class="line"><span class="keyword">var</span> clear = <span class="function"><span class="keyword">function</span>(<span class="params">el</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> id = el.id,</span><br><span class="line">        name = el.getAttribute(<span class="string">"data-name"</span>);</span><br><span class="line"></span><br><span class="line">    .........</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 不推荐的书写</span></span><br><span class="line"><span class="keyword">var</span> clear = <span class="function"><span class="keyword">function</span>(<span class="params">el</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> id = el.id;</span><br><span class="line"></span><br><span class="line">    ......</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> name = el.getAttribute(<span class="string">"data-name"</span>);</span><br><span class="line"></span><br><span class="line">    .........</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="块内函数必须用局部变量声明"><a href="#块内函数必须用局部变量声明" class="headerlink" title="块内函数必须用局部变量声明"></a>块内函数必须用局部变量声明</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 错误的写法</span></span><br><span class="line"> <span class="keyword">var</span> call = <span class="function"><span class="keyword">function</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">     <span class="keyword">if</span> (name == <span class="string">"hotel"</span>) &#123;</span><br><span class="line">         <span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">             <span class="built_in">console</span>.log(<span class="string">"hotel foo"</span>);</span><br><span class="line">         &#125;</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     foo &amp;&amp; foo();</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="comment">// 推荐的写法</span></span><br><span class="line"> <span class="keyword">var</span> call = <span class="function"><span class="keyword">function</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">     <span class="keyword">var</span> foo;</span><br><span class="line"></span><br><span class="line">     <span class="keyword">if</span> (name == <span class="string">"hotel"</span>) &#123;</span><br><span class="line">         foo = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">             <span class="built_in">console</span>.log(<span class="string">"hotel foo"</span>);</span><br><span class="line">         &#125;</span><br><span class="line">     &#125;</span><br><span class="line"></span><br><span class="line">     foo &amp;&amp; foo();</span><br><span class="line"> &#125;</span><br><span class="line"><span class="string">``</span><span class="string">` </span></span><br><span class="line"><span class="string">引起的bug：第一种写法foo的声明被提前了; 调用call时：第一种写法会调用foo函数，第二种写法不会调用foo函数</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">注：不同浏览器解析不同，具体请移步汤姆大叔[深入解析Javascript函数篇](http://www.cnblogs.com/TomXu/archive/2012/01/30/2326372.html)</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">## 禁止）使用eval，采取$.parseJSON</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&gt; 三个原因：</span></span><br><span class="line"><span class="string">有注入风险，尤其是ajax返回数据</span></span><br><span class="line"><span class="string">不方便debug</span></span><br><span class="line"><span class="string">效率低，eval是一个执行效率很低的函数</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">建议：使用new Function来代替eval的使用，最好就别用。</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">## 除了三目运算，if,else等（禁止）简写</span></span><br><span class="line"><span class="string">`</span><span class="string">``</span>javascript</span><br><span class="line"> <span class="comment">// 正确的书写</span></span><br><span class="line"> <span class="keyword">if</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">     alert(name);</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="built_in">console</span>.log(name);</span><br><span class="line"> <span class="comment">// 不推荐的书写</span></span><br><span class="line"> <span class="keyword">if</span> (<span class="literal">true</span>)</span><br><span class="line">     alert(name);</span><br><span class="line"> <span class="built_in">console</span>.log(name);</span><br><span class="line"> <span class="comment">// 不推荐的书写</span></span><br><span class="line"> <span class="keyword">if</span> (<span class="literal">true</span>)</span><br><span class="line"> alert(name);</span><br><span class="line"> <span class="built_in">console</span>.log(name)</span><br></pre></td></tr></table></figure>
<h2 id="（推荐）在需要以-闭合的代码段前增加换行，如：for-if"><a href="#（推荐）在需要以-闭合的代码段前增加换行，如：for-if" class="headerlink" title="（推荐）在需要以{}闭合的代码段前增加换行，如：for if"></a>（推荐）在需要以{}闭合的代码段前增加换行，如：for if</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 没有换行，小的代码段无法区分</span></span><br><span class="line"><span class="keyword">if</span> (wl &amp;&amp; wl.length) &#123;</span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>, l = wl.length; i &lt; l; ++i) &#123;</span><br><span class="line">        p = wl[i];</span><br><span class="line">        type = Y.Lang.type(r[p]);</span><br><span class="line">        <span class="keyword">if</span> (s.hasOwnProperty(p)) &#123;</span><br><span class="line">            <span class="keyword">if</span> (merge &amp;&amp; type == <span class="string">'object'</span>) &#123;</span><br><span class="line">                Y.mix(r[p], s[p]);</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (ov || !(p in r)) &#123;</span><br><span class="line">                r[p] = s[p];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 有了换行，逻辑清楚多了</span></span><br><span class="line"><span class="keyword">if</span> (wl &amp;&amp; wl.length) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>, l = wl.length; i &lt; l; ++i) &#123;</span><br><span class="line">        p = wl[i];</span><br><span class="line">        type = Y.Lang.type(r[p]);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (s.hasOwnProperty(p)) &#123;</span><br><span class="line">            <span class="comment">// 处理merge逻辑</span></span><br><span class="line">            <span class="keyword">if</span> (merge &amp;&amp; type == <span class="string">'object'</span>) &#123;</span><br><span class="line">                Y.mix(r[p], s[p]);</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (ov || !(p in r)) &#123;</span><br><span class="line">                r[p] = s[p];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>换行可以是空行，也可以是注释</p>
<h2 id="推荐）使用Function进行类的定义，-不推荐-继承，如需继承采用成熟的类库实现继承"><a href="#推荐）使用Function进行类的定义，-不推荐-继承，如需继承采用成熟的类库实现继承" class="headerlink" title="(推荐）使用Function进行类的定义，(不推荐)继承，如需继承采用成熟的类库实现继承"></a>(推荐）使用Function进行类的定义，(不推荐)继承，如需继承采用成熟的类库实现继承</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 类的实现</span></span><br><span class="line"> <span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">     <span class="keyword">this</span>.name = name;</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> Person.prototype.sayName = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">     alert(<span class="keyword">this</span>.name);</span><br><span class="line"> &#125;;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">var</span> me = <span class="keyword">new</span> Person(<span class="string">"Nicholas"</span>);</span><br><span class="line"></span><br><span class="line"> <span class="comment">// 将this放到局部变量self</span></span><br><span class="line"> <span class="function"><span class="keyword">function</span> <span class="title">Persion</span>(<span class="params">name, sex</span>) </span>&#123;</span><br><span class="line">     <span class="keyword">var</span> self = <span class="keyword">this</span>;</span><br><span class="line"></span><br><span class="line">     self.name = name;</span><br><span class="line">     self.sex = sex;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p> 平时咱们写代码，基本都是小程序，真心用不上什么继承，而且继承并不是JS的擅长的语言特性，尽量少用。如果非要使用的话，注意一点：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"> <span class="function">function <span class="title">A</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="function">function <span class="title">B</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">&#125;</span><br><span class="line">B.prototype = <span class="keyword">new</span> A();</span><br><span class="line">B.prototype.constructor = B; <span class="comment">//原则上，记得把这句话加上</span></span><br></pre></td></tr></table></figure><br> 继承从原则上来讲，别改变他的构造函数，否则这个继承就显得很别扭了~ </p>
<h2 id="推荐-使用局部变量缓存反复查找的对象-包括但不限于全局变量、dom查询结果、作用域链较深的对象"><a href="#推荐-使用局部变量缓存反复查找的对象-包括但不限于全局变量、dom查询结果、作用域链较深的对象" class="headerlink" title="(推荐)使用局部变量缓存反复查找的对象(包括但不限于全局变量、dom查询结果、作用域链较深的对象)"></a>(推荐)使用局部变量缓存反复查找的对象(包括但不限于全局变量、dom查询结果、作用域链较深的对象)</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">// 缓存对象</span></span><br><span class="line"> <span class="keyword">var</span> getComment = function() &#123;</span><br><span class="line">     <span class="keyword">var</span> dom = $(<span class="string">"#common-container"</span>),               <span class="comment">// 缓存dom</span></span><br><span class="line">         appendTo = $.appendTo,                      <span class="comment">// 缓存全局变量</span></span><br><span class="line">         data = <span class="keyword">this</span>.json.data;                      <span class="comment">// 缓存作用域链较深的对象</span></span><br><span class="line"></span><br><span class="line"> &#125;</span><br><span class="line">``` </span><br><span class="line"></span><br><span class="line">## 当需要缓存this时必须使用self变量进行缓存</span><br><span class="line">```java</span><br><span class="line"><span class="comment">// 缓存this</span></span><br><span class="line"> <span class="function">function <span class="title">Row</span><span class="params">(name)</span> </span>&#123;</span><br><span class="line">     <span class="keyword">var</span> self = <span class="keyword">this</span>;</span><br><span class="line"></span><br><span class="line">     self.name = name;</span><br><span class="line">     $(<span class="string">".row"</span>).click(function() &#123;</span><br><span class="line">         self.getName();</span><br><span class="line">     &#125;);</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p> self是一个保留字，不过用它也没关系。在这里，看个人爱好吧，可以用_this, that, me等这些词，都行，但是团队开发的时候统一下比较好。</p>
<p>##（不推荐）超长函数, 当函数超过100行，就要想想是否能将函数拆为两个或多个函数</p>
<p><a href="http://www.cnblogs.com/hustskyking/p/javascript-spec.html" target="_blank" rel="noopener">原文地址</a></p>

            <!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
            <audio id="audio" loop="1" preload="auto" controls="controls"
                data-autoplay="false">
                <source type="audio/mpeg" src="">
            </audio>
            
            <ul id="audio-list" style="display:none">
                
                
                <li title='0' data-url='/statics/chengdu.mp3'></li>
                
                    
            </ul>
            
            
            
    <div id='gitalk-container' class="comment link"
        data-ae='true'
        data-ci='ec894e2b66f752e8b7fb'
        data-cs='3ccc2e92bb350688fe2c2dc2930189b62622bfb1'
        data-r='blog-comments'
        data-o='TriDiamond'
        data-a='TriDiamond'
        data-d='undefined'
    >Comments</div>


            
            
        </div>
        <div class="sidebar">
            <div class="box animated fadeInRight">
                <div class="subbox">
                    <img src="https://res.cloudinary.com/tridiamond/image/upload/v1573019751/TriDiamond_logo_ui_xeublz.jpg" height=300 width=300></img>
                    <p>张白告丶</p>
                    <span>Think like an artist, develop like an artisan</span>
                    <dl>
                        <dd><a href="https://github.com/zhanghao-web" target="_blank"><span
                                    class=" iconfont icon-github"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-twitter"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-stack-overflow"></span></a></dd>
                    </dl>
                </div>
                <ul>
                    <li><a href="/">149 <p>Articles</p></a></li>
                    <li><a href="/categories">23 <p>Categories</p></a></li>
                    <li><a href="/tags">47 <p>Tags</p></a></li>
                </ul>
            </div>
            
            
            
            <div class="box sticky animated fadeInRight faster">
                <div id="toc" class="subbox">
                    <h4>Contents</h4>
                    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#不规范写法举例"><span class="toc-number">1.</span> <span class="toc-text">不规范写法举例</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#前端规范之JavaScript"><span class="toc-number">2.</span> <span class="toc-text">前端规范之JavaScript</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#变量、常量、类的命名按（必须）以下规则执行："><span class="toc-number">2.1.</span> <span class="toc-text">变量、常量、类的命名按（必须）以下规则执行：</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#if中的空格，先上例子"><span class="toc-number">2.2.</span> <span class="toc-text">if中的空格，先上例子</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#for中的空格，先上例子"><span class="toc-number">2.3.</span> <span class="toc-text">for中的空格，先上例子</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#var-中空格及定义，先上例子"><span class="toc-number">2.4.</span> <span class="toc-text">var 中空格及定义，先上例子</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#在同一个函数内部，局部变量的声明必须置于顶端"><span class="toc-number">2.5.</span> <span class="toc-text">在同一个函数内部，局部变量的声明必须置于顶端</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#块内函数必须用局部变量声明"><span class="toc-number">2.6.</span> <span class="toc-text">块内函数必须用局部变量声明</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#（推荐）在需要以-闭合的代码段前增加换行，如：for-if"><span class="toc-number">2.7.</span> <span class="toc-text">（推荐）在需要以{}闭合的代码段前增加换行，如：for if</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#推荐）使用Function进行类的定义，-不推荐-继承，如需继承采用成熟的类库实现继承"><span class="toc-number">2.8.</span> <span class="toc-text">(推荐）使用Function进行类的定义，(不推荐)继承，如需继承采用成熟的类库实现继承</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#推荐-使用局部变量缓存反复查找的对象-包括但不限于全局变量、dom查询结果、作用域链较深的对象"><span class="toc-number">2.9.</span> <span class="toc-text">(推荐)使用局部变量缓存反复查找的对象(包括但不限于全局变量、dom查询结果、作用域链较深的对象)</span></a></li></ol></li></ol>
                </div>
            </div>
            
            
        </div>
    </div>
</div>

    </div>
</div>
    <div id="back-to-top" class="animated fadeIn faster">
        <div class="flow"></div>
        <span class="percentage animated fadeIn faster">0%</span>
        <span class="iconfont icon-top02 animated fadeIn faster"></span>
    </div>
</body>
<footer>
    <p class="copyright" id="copyright">
        &copy; 2020
        <span class="gradient-text">
            张白告丶
        </span>.
        Powered by <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a>
        Theme
        <span class="gradient-text">
            <a href="https://github.com/TriDiamond/hexo-theme-obsidian" title="Obsidian" target="_blank" rel="noopener">Obsidian</a>
        </span>
        <small><a href="https://github.com/TriDiamond/hexo-theme-obsidian/blob/master/CHANGELOG.md" title="v1.4.3" target="_blank" rel="noopener">v1.4.3</a></small>
    </p>
</footer>

<script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.6/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<script>
  MathJax.Hub.Config({
    "HTML-CSS": {
      preferredFont: "TeX",
      availableFonts: ["STIX", "TeX"],
      linebreaks: {
        automatic: true
      },
      EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50)
    },
    tex2jax: {
      inlineMath: [
        ["$", "$"],
        ["\\(", "\\)"]
      ],
      processEscapes: true,
      ignoreClass: "tex2jax_ignore|dno",
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      noUndefined: {
        attributes: {
          mathcolor: "red",
          mathbackground: "#FFEEEE",
          mathsize: "90%"
        }
      },
      Macros: {
        href: "{}"
      }
    },
    messageStyle: "none"
  });
</script>
<script>
  function initialMathJax() {
    MathJax.Hub.Queue(function () {
      var all = MathJax.Hub.getAllJax(),
        i;
      // console.log(all);
      for (i = 0; i < all.length; i += 1) {
        console.log(all[i].SourceElement().parentNode)
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  }

  function reprocessMathJax() {
    if (typeof MathJax !== 'undefined') {
      MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
    }
  }
</script>



    
<link rel="stylesheet" href="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.css">

    
<script src="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.js"></script>



<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/js/plugin.js"></script>
<script src="/js/obsidian.js"></script>
<script src="/js/jquery.truncate.js"></script>
<script src="/js/search.js"></script>


<script src="//cdn.bootcss.com/typed.js/2.0.10/typed.min.js"></script>


<script src="//cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script>


<script src="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js"></script>


<script src="https://cdn.bootcss.com/codemirror/5.48.4/codemirror.min.js"></script>

    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/javascript/javascript.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/css/css.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/xml/xml.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/htmlmixed/htmlmixed.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/clike/clike.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/php/php.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/shell/shell.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/python/python.min.js"></script>




    
<script src="/js/busuanzi.min.js"></script>

    <script>
        $(document).ready(function () {
            if ($('span[id^="busuanzi_"]').length) {
                initialBusuanzi();
            }
        });
    </script>



<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.css">
<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/default-skin/default-skin.min.css">


<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.js"></script>
<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe-ui-default.min.js"></script>


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>



    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="//www.googletagmanager.com/gtag/js?id=UA-149874671-1"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-149874671-1');
    </script>





<script>
    function initialTyped () {
        var typedTextEl = $('.typed-text');
        if (typedTextEl && typedTextEl.length > 0) {
            var typed = new Typed('.typed-text', {
                strings: ["Think like an artist, develop like an artisan", "艺术家思维去思考问题，工匠创造精神去开发"],
                typeSpeed: 90,
                loop: true,
                loopCount: Infinity,
                backSpeed: 20,
            });
        }
    }

    if ($('.article-header') && $('.article-header').length) {
        $(document).ready(function () {
            initialTyped();
        });
    }
</script>




</html>
